package br.com.management.mentor.app.components;

import java.util.List;
import java.util.Locale;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.springframework.context.ApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.management.mentor.view.core.View;
import br.com.management.mentor.view.core.ViewExceptionHandler;

public class PopupExceptionHandler implements ViewExceptionHandler {

	@Autowired
	private Locale locale;

	@Autowired
	private ApplicationContext context;

	@Autowired
	private List<ExceptionMessageExtractor> messageExtractors;

	@Override
	public void handle( Exception e , View view ) {
		
		String message = null;
		for ( ExceptionMessageExtractor eME : getMessageExtractors() ) {
			if( eME.canHandle( e ) ) {
				message = eME.getMessage( e );
				break;
			}
		}
		
		if( message == null ) message = e.getMessage();
		
		MessageBox popup = new MessageBox( view.getParent() , SWT.ICON_ERROR | SWT.OK );
		popup.setText( context.getMessage( "popup.validation.title" , null , locale ) );
		popup.setMessage( message );
		
		popup.open();
	}

	public List<ExceptionMessageExtractor> getMessageExtractors() {
		return messageExtractors;
	}

	public void setMessageExtractors( List<ExceptionMessageExtractor> messageExtractors ) {
		this.messageExtractors = messageExtractors;
	}
	
}